package bblrtc

import (
	"code.google.com/p/go-uuid/uuid"
	"github.com/robfig/config"
	"hash/fnv"
	"log"
	"os"
	"time"
)

var conf_file string
var syslog *log.Logger
var imlog *log.Logger
var conf *config.Config
var UDB *RegisterDB

func UUID() string {
	return uuid.NewUUID().String()
}

func Today() string {
	return time.Now().Format("2006-01-02")
}

func Datetime() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

func FormatTime(t time.Time) string {
	return t.Format("2006-01-02 15:04:05")
}

func Hash(s string) uint32 {
	h := fnv.New32a()
	h.Write([]byte(s))
	return h.Sum32()
}

func Init(conf string) error {
	if err := initConfig(conf); err != nil {
		return err
	}
	if err := initLog(GetString("main", "sys_log_file", "stdout"), GetString("main", "im_log_file", "stdout")); err != nil {
		return err
	}
	if db, err := NewUDB(GetString("main", "work_dir", "work") + "/imdb.db"); err != nil {
		syslog.Println(err)
		return err
	} else {
		UDB = db
	}
	return nil
}

func initConfig(file string) (err error) {
	if c, err := config.ReadDefault(file); err == nil {
		conf = c
		conf_file = file
	}
	return err
}

func GetString(section, key, def string) string {
	if conf == nil {
		return def
	}
	if v, err := conf.String(section, key); err != nil {
		return def
	} else {
		return v
	}
}

func GetInt(section, key string, def int) int {
	if conf == nil {
		return def
	}
	if v, err := conf.Int(section, key); err != nil {
		return def
	} else {
		return v
	}
}

func GetFloat64(section, key string, def float64) float64 {
	if conf == nil {
		return def
	}
	if v, err := conf.Float(section, key); err != nil {
		return def
	} else {
		return v
	}
}

func GetBool(section, key string, def bool) bool {
	if conf == nil {
		return def
	}
	if v, err := conf.Bool(section, key); err != nil {
		return def
	} else {
		return v
	}
}

func initLog(sysfile, imfile string) error {
	if "" == sysfile || "stdout" == sysfile {
		syslog = log.New(os.Stdout, "", log.Ldate|log.Ltime)
	} else {
		fi, err := os.OpenFile(sysfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			return err
		}

		syslog = log.New(fi, "", log.Ldate|log.Ltime)
	}
	if "" == imfile || "stdout" == imfile {
		imlog = log.New(os.Stdout, "", log.Ldate|log.Ltime)
	} else {
		fi, err := os.OpenFile(imfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			return err
		}

		imlog = log.New(fi, "", log.Ldate|log.Ltime)
	}
	return nil
}
